
package com.example.androidmychapter;


import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.androidmychapter.Adapter.Myadpater;
import com.example.androidmychapter.Service.MyService;
import com.example.androidmychapter.util.RecordingUtil;

import java.io.File;
import java.util.List;

public class MainActivity2 extends AppCompatActivity {
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
    private static final int PERMISSION_REQUEST_CODE = 201;
    private static final int REQUEST_MANAGE_EXTERNAL_STORAGE_CODE = 1;
    private static final int REQUEST_CODE = 2;
    private String outputFile;
    private MediaRecorder mediaRecorder;
    private ImageButton btnStartRecording;
    private ImageButton btnStopRecording;
    private boolean isRecording = false;
    private Chronometer chronometer;
    private ListView lv_recording;
    private List<String> arryList;
    private RecordingUtil recordingUtil;
    private Myadpater myadpater;
    private MediaPlayer mediaPlayer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        //创建目录
        checkAndRequestPermissions();


        //数据实时更新
        final Handler handler = new Handler();
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // 更新数据的方法
                updateData();
                // 每1秒刷新一次
                handler.postDelayed(this, 1000);
            }

            private void updateData() {
                myadpater.notifyDataSetChanged();
            }
        };

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            // 如果没有权限，则请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.RECORD_AUDIO},
                    PERMISSION_REQUEST_CODE);
        }
        //录音数组
        arryList = RecordingUtil.getArryList();
        //计时器
        chronometer = findViewById(R.id.chronometer);
        //开始录音
        recordingUtil = new RecordingUtil();
        btnStartRecording = findViewById(R.id.btnStartRecording);
        //结束录音
        btnStopRecording = findViewById(R.id.btnStopRecording);
        //录音列表
        lv_recording = findViewById(R.id.lv_recording);
        myadpater = new Myadpater(MainActivity2.this, arryList);
        lv_recording.setAdapter(myadpater);
        lv_recording.setOnItemClickListener((parent, view, position, id) -> {
            // 创建一个选择框
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity2.this);
            builder.setTitle("播放还是删除")
                    .setItems(new String[]{"播放", "删除"}, new DialogInterface.OnClickListener() {
                        private VideoView videoView;

                        public void onClick(DialogInterface dialog, int which) {
                            // 处理选择的选项
                            switch (which) {
                                case 0:
                                    playRecording();
                                    break;
                                case 1:
                                    deleteRecording(position);
                                    break;
                            }
                        }

                        private void playRecording() {
                            File s = new File(arryList.get(position));
                            videoView = findViewById(R.id.videoView);
                            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(MainActivity2.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
                            } else {
                                String videoPath = s.getAbsolutePath();
                                //检查文件是否可读取
                                videoView.setVideoPath(videoPath);
                                videoView.setOnPreparedListener(mp -> {
                                    Log.d("VideoPlayer", "Video prepared");
                                    videoView.start();
                                });

                                videoView.setOnCompletionListener(mp -> {
                                    Log.d("VideoPlayer", "Playback completed");
                                    Toast.makeText(MainActivity2.this, "播放完成", Toast.LENGTH_SHORT).show();
                                });

                                videoView.setOnErrorListener((mp, what, extra) -> {
                                    Log.e("VideoPlayer", "Error playing video: what=" + what + ", extra=" + extra);
                                    Toast.makeText(MainActivity2.this, "无法播放视频", Toast.LENGTH_SHORT).show();
                                    return true;
                                });
                            }
                        }


                        private void deleteRecording(int position) {
                            String s = arryList.get(position);
                            arryList.remove(position);
                            File file = new File(s);
                            file.delete();
                            handler.post(runnable);
                        }
                    });
            builder.create().show();
        });

        btnStartRecording.setOnClickListener(v -> {
            handler.removeCallbacks(runnable);
            chronometer.setBase(SystemClock.elapsedRealtime());
            chronometer.start();
            btnStartRecording.setVisibility(View.INVISIBLE);
            btnStopRecording.setVisibility(View.VISIBLE);

            Intent startIntent = new Intent(MainActivity2.this, MyService.class);
            startService(startIntent);

        });
        btnStopRecording.setOnClickListener(v -> {
            handler.post(runnable);
            chronometer.stop();
            chronometer.setBase(SystemClock.elapsedRealtime());
            btnStartRecording.setVisibility(View.VISIBLE);
            btnStopRecording.setVisibility(View.INVISIBLE);

            Intent stopIntent = new Intent(MainActivity2.this, MyService.class);
            stopService(stopIntent);
        });
    }

    private void checkAndRequestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                startActivityForResult(intent, REQUEST_MANAGE_EXTERNAL_STORAGE_CODE);
            } else {
                readSDCard();
            }
        } else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
            } else {
                readSDCard();
            }
        }
    }

    private void readSDCard() {
        File directory = new File(Environment.getExternalStorageDirectory(), "YourDirectory");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(MainActivity2.class.getSimpleName(), "onActivityResult: " + requestCode);
        if (requestCode == REQUEST_MANAGE_EXTERNAL_STORAGE_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    readSDCard();
                } else {
                    Toast.makeText(this, "Manage External Storage Permission Denied", Toast.LENGTH_SHORT).show();
                }
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            } else {
                Toast.makeText(this, "奇怪啊", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
}